import {
  app,
  BrowserWindow,
  dialog,
  globalShortcut,
  ipcMain,
  IpcMainInvokeEvent,
  Notification
} from 'electron'

export function registerShortCut(win: BrowserWindow) {
  ipcMain.handle('shortCut', (_event: IpcMainInvokeEvent, type: string, shortCut: string) => {
    switch (type) {
      case 'search': {
        const isRegister = registerSearch(win, shortCut)
        if (isRegister) {
          new Notification({ title: '快捷键注册成功', body: `当前快捷键位${shortCut}` }).show()
        }
        return isRegister
      }
      default: {
        return true
      }
    }
  })
}

function registerSearch(win: BrowserWindow, shortCut: string) {
  globalShortcut.unregisterAll()
  if (shortCut && globalShortcut.isRegistered(shortCut)) {
    dialog.showErrorBox('温馨提示', '快捷键注册失败，请检查快捷键是否已被占用')
    return false
  }
  return globalShortcut.register(shortCut, () => {
    win.isVisible() ? win.hide() : win.show()
  })
}

app.on('will-quit', () => {
  // 注销快捷键
  // globalShortcut.unregister('CommandOrControl+X')

  // 注销所有快捷键
  globalShortcut.unregisterAll()
})
